<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>shell | 学习笔记</title><meta name="author" content="lzoxun"><meta name="copyright" content="lzoxun"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="shell 脚本概述 ls(命令) -&gt; shell(bash、zsh) -&gt; 内核(kemel) -&gt; 硬件 ls:用户使用文字或图形界面操作操作系统 shell:接受与来自用户的命令与内核进行沟通，是用户与内核沟通的接口程序 内核:控制硬件进行工作，进程管理储存管理等   shell对本质是对内核进行保护，只有shell能识别的命令才能用了操控硬件 脚本语言不需要 编译,把命">
<meta property="og:type" content="article">
<meta property="og:title" content="shell">
<meta property="og:url" content="http://example.com/2023/07/22/linux/linux-shell/index.html">
<meta property="og:site_name" content="学习笔记">
<meta property="og:description" content="shell 脚本概述 ls(命令) -&gt; shell(bash、zsh) -&gt; 内核(kemel) -&gt; 硬件 ls:用户使用文字或图形界面操作操作系统 shell:接受与来自用户的命令与内核进行沟通，是用户与内核沟通的接口程序 内核:控制硬件进行工作，进程管理储存管理等   shell对本质是对内核进行保护，只有shell能识别的命令才能用了操控硬件 脚本语言不需要 编译,把命">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png">
<meta property="article:published_time" content="2023-07-22T07:14:09.681Z">
<meta property="article:modified_time" content="2023-07-22T07:14:09.681Z">
<meta property="article:author" content="lzoxun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2023/07/22/linux/linux-shell/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":true,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'shell',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-07-22 15:14:09'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">108</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="学习笔记"><span class="site-name">学习笔记</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">shell</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-07-22T07:14:09.681Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-07-22T07:14:09.681Z" title="更新于 2023-07-22 15:14:09">2023-07-22</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="shell"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="shell-脚本"><a href="#shell-脚本" class="headerlink" title="shell 脚本"></a>shell 脚本</h2><h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><ul>
<li>ls(命令) -&gt; shell(bash、zsh) -&gt; 内核(kemel) -&gt; 硬件<ul>
<li><code>ls</code>:用户使用文字或图形界面操作操作系统</li>
<li><code>shell</code>:接受与来自用户的命令与内核进行沟通，是<code>用户</code>与<code>内核沟通</code>的接口程序</li>
<li><code>内核</code>:控制硬件进行工作，进程管理储存管理等</li>
</ul>
</li>
<li>shell对本质是<code>对内核进行保护</code>，只有<code>shell能识别</code>的命令才能用了操控硬件</li>
<li>脚本语言<code>不需要</code> 编译,把命令写在文件中就是shell脚本了</li>
<li><code>shell脚本</code>是shell命令的<code>有序集合</code></li>
<li><code>系统编程</code>:主要为了让用户更好更方便的操作硬件设备，并且对硬件也起到保护作用，我们所写的程序，本质就是对硬件进行操作，所以操作系统提供的接口本来就能对硬件进行操作的</li>
<li><code>系统调用</code>: <ul>
<li>步骤: shell、library rou(库函数)、applications(应用层接口) -&gt; system calls(系统调用，提供直接操作内核的特殊接口) -&gt; kernel(内核) -&gt; 操作硬件设备</li>
</ul>
</li>
<li>shell优势，处理操作系统底层的业务（大量命令为他做支持，grep awk sed 等）</li>
</ul>
<h3 id="开启-shell"><a href="#开启-shell" class="headerlink" title="开启 shell"></a>开启 shell</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash   指定使用bash解释器,必须顶格,linux 默认bash</span></span><br><span class="line"></span><br><span class="line">指定脚本的执行方式</span><br><span class="line">1、开头 #！</span><br><span class="line">2、执行文件的时候 bash install.sh</span><br><span class="line">3、/bin/bash 终端默认使用 bash</span><br><span class="line"></span><br><span class="line">shell 脚本的执行</span><br><span class="line">1、调用相关环境变量文件，脚本里可以随意使用里面的数据</span><br><span class="line">    /home/xx/.bashrc (3)</span><br><span class="line">    /home/xx/.bash_profile </span><br><span class="line">    /etc/bashrc (4)</span><br><span class="line">    /etc/profile (2)</span><br><span class="line">    /etc/profile.d (优先级最高 1)</span><br><span class="line"></span><br><span class="line">2、执行shell的方式</span><br><span class="line">    bash shellfile | sh shellfile (脚本头没指定解释器)</span><br><span class="line">    path/shellfile | ./shellfile (没有x权限不能执行)</span><br><span class="line">    source shellfile | . shellfile（读入或加载指定shell脚本，可以将脚本中的变量传到当前shell里）</span><br><span class="line"></span><br><span class="line">3、基本规范</span><br><span class="line">    开头添加 #!/bin/bash 解释器</span><br><span class="line">    # Date 日期</span><br><span class="line">    # Author 作者</span><br><span class="line">    # Mail 联系方式</span><br><span class="line">    # Func 功能</span><br><span class="line">    # Version 版本 。。。</span><br><span class="line"></span><br><span class="line">    尽量不要用中文</span><br><span class="line">    扩展名以.sh结尾</span><br><span class="line">    成对的符号先敲好，不要一个个敲</span><br><span class="line">    [] 两端必须有空格($[]不算)</span><br><span class="line"></span><br><span class="line">cat /etc/passwd</span><br><span class="line">echo &quot;hello word&quot;</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">==================定义一个变量</span></span><br><span class="line">num=10 #等号左右不能有空格</span><br><span class="line">readonly age=20 #age不能被改变</span><br><span class="line">export name=&quot;name&quot; #name会被导出为环境变量,其他shell都能使用</span><br><span class="line">declare -i sum # sum是一个整数变量</span><br><span class="line"></span><br><span class="line">echo $num # 使用变量加$</span><br><span class="line">echo $&#123;num&#125;Addstring # 使用变量加$&#123;&#125;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">--- <span class="string">&quot;&quot;</span> 弱引用 里面可以读取变量</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">--- ``|$() 把里面的内容当中命令执行，得到执行返回的结果</span></span><br><span class="line">oa=&quot;this is $num ，`date`,$(date)&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">--- <span class="string">&#x27;&#x27;</span> 强引用 把动态的操作当成字符，</span></span><br><span class="line"></span><br><span class="line">unset num #清除变量</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">==================<span class="keyword">if</span>语句</span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash">用<span class="keyword">do</span> 和 down 表示其他语言的&#123;&#125;</span></span><br><span class="line"></span><br><span class="line">if [ 表达式 ]</span><br><span class="line">then</span><br><span class="line">    echo &quot;yes&quot;</span><br><span class="line">elif [ 表达式 ];then</span><br><span class="line">    echo &quot;noyes nono&quot;</span><br><span class="line">else</span><br><span class="line">    echo &quot;no&quot;</span><br><span class="line">fi  # 结束语句</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">if $num</span><br><span class="line">then</span><br><span class="line">    echo &quot;num is true&quot;</span><br><span class="line">elif $&#123;num1&#125;;then</span><br><span class="line">    echo &quot;num1 is true&quot;</span><br><span class="line">else</span><br><span class="line">    echo &quot;no&quot;</span><br><span class="line">fi  # 结束语句</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">================== <span class="keyword">case</span></span></span><br><span class="line">read -p &quot;请输入任意字符&quot; key</span><br><span class="line">case &quot;$key&quot; in</span><br><span class="line">    [a-z]|[A-Z])</span><br><span class="line">        echo &quot;这是英文字母&quot;</span><br><span class="line">        ;;</span><br><span class="line">    [0-9])</span><br><span class="line">        echo &quot;这是一个数字&quot;</span><br><span class="line">        ;;</span><br><span class="line">    *)</span><br><span class="line">        echo &quot;这是一个其他字符&quot;</span><br><span class="line">esac</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">================== <span class="keyword">for</span> 循环</span></span><br><span class="line">for(( i=1; i&lt;=100; i++ ))</span><br><span class="line">do</span><br><span class="line">    echo $i</span><br><span class="line">done</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">================== <span class="keyword">for</span> <span class="keyword">in</span></span></span><br><span class="line">for i in 1 2 3 4 5</span><br><span class="line">do</span><br><span class="line">    echo $i</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line">for i in 1 2 3 4 5</span><br><span class="line">do</span><br><span class="line">     echo $i &amp;  #相当于多进程并发执行 ，适合耗时长，后面程序不依赖当前结果，且计算机资源足够的时候</span><br><span class="line">     # 线程是进程的一部分，shell只能多进程，多线程需要Python的高级语言</span><br><span class="line">     # 这边只适合一条语句，如果复杂可以放到函数里 funcName 12 &amp;</span><br><span class="line">done</span><br><span class="line">wait # 等待循环体全部执行完再做后面事情</span><br><span class="line">xxx</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">列表</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">&#123;1..5&#125; 1-5</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">$(<span class="built_in">ls</span> /etc)</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">================================= <span class="keyword">while</span></span></span><br><span class="line">i=1</span><br><span class="line">while [ $i -le 100 ]</span><br><span class="line">do</span><br><span class="line">    echo $i</span><br><span class="line">    i=$[$i + 1]</span><br><span class="line">    或 i=`expr $i+1`</span><br><span class="line">    或 i=$(( $i+1 ))</span><br><span class="line">done</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">操作文件</span></span><br><span class="line">while read line</span><br><span class="line">do</span><br><span class="line">    echo &quot;$&#123;line&#125;-change&quot;</span><br><span class="line">done &lt; /etc/passwd</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash"><span class="keyword">until</span></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">与<span class="keyword">while</span>循环相反，测试成立才退出循环</span></span><br><span class="line">i=1</span><br><span class="line">until [ $i -le 100 ]</span><br><span class="line">do</span><br><span class="line">    echo $i</span><br><span class="line">    i=$[$i + 1]</span><br><span class="line">done</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">================================== 函数</span></span><br><span class="line">function name &#123; xxx &#125;</span><br><span class="line">name()&#123; </span><br><span class="line">   SUM=$[$1+$2]</span><br><span class="line">   return SUM</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">name 1 2  # 通过位置变量接收参数</span><br><span class="line">echo &quot;$?&quot; #获取返回值方式最大255</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">在shell中处理()中定义的变量，只要不做任何修饰，都能看做是全局变量</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">==================总结</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">指定解释器的地方</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">1、shell文件顶端；2、bash shell.sh；3、通过路径执行脚本的终端；</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">2、分号可以合并多行，或者一行执行多条命令</span></span><br></pre></td></tr></table></figure>

<h3 id="执行"><a href="#执行" class="headerlink" title="执行"></a>执行</h3><ul>
<li>echp $PATH</li>
<li>存放外部命令的路径</li>
<li>访问命令就可以省去前面的路径直接写名字</li>
<li>一个<code>shell脚本</code>可以看做一个命令</li>
<li>如果没在<code>$PATH</code>里的路径下,就需要<code>加上绝对路径</code>或<code>相对路径执行</code>才能执行,</li>
<li>或直接通过<code>/etc/shells</code>下的解释器直接执行脚本</li>
<li><code>bash shells.sh</code> -<code>-n</code>:检查错误 -<code>-x</code>:将脚本中执行的命令也打印出来</li>
</ul>
<h3 id="常用的-bash-语句"><a href="#常用的-bash-语句" class="headerlink" title="常用的 bash 语句"></a>常用的 bash 语句</h3><ul>
<li>shift 从前面删除一个位置变量</li>
<li>export 定义环境变量</li>
</ul>
<h3 id="语法"><a href="#语法" class="headerlink" title="语法"></a>语法</h3><ul>
<li>特殊符号<ul>
<li><code>\</code>:<code>echo -e &quot;this \n towline&quot;</code> 配合 -e 生效 </li>
<li><code>(xxx)</code>:小括号会创建一个子shell，里面操作不会影响当前shell</li>
<li><code>&#123;xxx&#125;</code>:大括号里的操作会音响当前shell</li>
</ul>
</li>
<li>算术运算符(<code>+、-、*、/、%、**</code>)<ul>
<li><code>$[$a+$b]</code>:运算+不能直接用,<code>$[]</code>或<code>$(())</code>或<code>expr 1 + 2</code>里的东西当做运算处理’</li>
</ul>
</li>
<li>变量<ul>
<li><code>普通变量(只能在函数或脚本中用)</code><ul>
<li>num&#x3D;1</li>
<li>命令定义成变量 xxx&#x3D;<code>date +%F</code>| xxx&#x3D;$(date +%F)   echo $xxx</li>
</ul>
</li>
<li><code>环境变量(全局变量，能在创建他们的shell和他们的子shell中用)</code><ul>
<li><p>一般大写表示</p>
</li>
<li><p>常用环境变量</p>
<ul>
<li><p><code>$PATH</code>:用户命令路径</p>
</li>
<li><p><code>$SHELL</code>:用户使用的 shell</p>
</li>
<li><p><code>$HISTSIZE</code>:history 查看历史命令，这个可以查看 history 上限</p>
</li>
<li><p><code>$USER</code>:获取当前用户的名称</p>
</li>
<li><p><code>$HOME</code>:获取当前用户加</p>
</li>
<li><p><code>$PWD</code>:获取当前用户工作目录</p>
</li>
<li><p><code>$UID</code>:获取当前用户的 ID</p>
</li>
<li><p><code>$LANG</code>:语言</p>
</li>
<li><p><code>$SHLVL</code>:bash实例个数</p>
</li>
<li><p><code>$TMOUT</code>:多少秒没操作就自动退出</p>
</li>
<li><p><code>$PS1</code>:定义终端用户信息格式</p>
</li>
</ul>
</li>
<li><p>临时更改: PATH &#x3D; xxxx</p>
</li>
<li><p>取消环境变量：unset 变量名</p>
</li>
<li><p>定义环境变量</p>
<ul>
<li><code>export NAME=&quot;name&quot;</code>:NAM 只有当前 shell 和子 shell 生效</li>
<li>添加扩展PATH:export PATH&#x3D;”&#x2F;home&#x2F;tuotu&#x2F;bin:$PATH”</li>
<li>永久设置<ul>
<li><code>bashrc</code>：用户登录、打开 shell、开子 shell 都会执行<ul>
<li><code>/etc/bashrc</code></li>
<li><code>~/.bashrc</code></li>
</ul>
</li>
<li><code>profile</code>:只在用户登录时执行一次<ul>
<li><code>/etc/profile</code>:全局</li>
<li><code>/etc/profile.d/*.sh</code>:优先级高，所有符合条件的文件开机都会执行一次</li>
<li><code>~/.bash_profile</code>:局部的</li>
</ul>
</li>
<li><code>source|. filename</code>:都能重新加载文件</li>
</ul>
</li>
</ul>
</li>
<li><p><code>env|set|export|printenv</code> 查看系统所有环境变量</p>
</li>
<li><p>大概顺序 etc&#x2F;profile → &#x2F;etc&#x2F;profile.d&#x2F;*.sh → ~&#x2F;.bash_profile → ~&#x2F;.bashrc → [&#x2F;etc&#x2F;bashrc]</p>
</li>
</ul>
</li>
<li><code>位置变量$1-$9</code>:接收用户执行脚本的传参，超过9 <code>$&#123;10,...&#125;</code></li>
<li><code>预定于变量</code><ul>
<li><code>$?</code>:0:上一条命令执行结果为真,否则执行为假[ -z $1 ]<ul>
<li>0 上条执行成功</li>
<li>2 权限拒绝</li>
<li>1-125 运行失败，命令错误 参数错误等</li>
<li>126 找到该命令，但是无法执行</li>
<li>127 未找到运行的命令</li>
</ul>
</li>
<li><code>$#</code>:表示位置参数数量</li>
<li><code>$0</code>:当前脚本的名称<ul>
<li>dirname $0 :获取整个路径</li>
<li>basename $0 :只获取文件名</li>
</ul>
</li>
<li><code>$@</code>:保存除$0外的所有参数<ul>
<li>每个参数都是单独的(数组形式)</li>
</ul>
</li>
<li><code>$*</code>:打印除了$0所有具体的参数<ul>
<li>所有参数视为一个参数</li>
</ul>
</li>
<li><code>$$</code>:获取当前进程的进程号</li>
<li><code>$!</code>:上一个指令的PID</li>
</ul>
</li>
</ul>
</li>
<li>条件测试与比较 <code>[ 条件表达式 ]</code> | <code>test -d $1</code><ul>
<li>解释<ul>
<li><code>[ 条件表达式 ]</code></li>
<li><code>[[ 条件表达式 ]]</code>:这种支持传统的大于小于号</li>
<li>中括号两边必须存在空格</li>
</ul>
</li>
<li>检测<ul>
<li><code>[ -d $1 ]</code>:检测参数一是否为目录</li>
<li><code>[ -f $1 ]</code>:检测参数一是否为文件</li>
<li><code>[ -e $1 ]</code>:检测母乳或文件是否存在</li>
<li><code>[ -r $1 ]</code>:</li>
<li><code>[ -x $1 ]</code>:</li>
<li><code>[ -w $1 ]</code>:检测用户是否有写入权限</li>
<li><code>[ -s $1 ]</code>:检测文件是否为空</li>
<li>文件类型按ll第一位的文件类型检测</li>
</ul>
</li>
<li>数值比较<ul>
<li><code>-eq</code>:等于</li>
<li><code>-ne</code>:不等于</li>
<li><code>-gt</code>:大于</li>
<li><code>-lt</code>:小于</li>
<li><code>-le</code>:小于等于</li>
<li><code>-ge</code>:大于等于</li>
</ul>
</li>
<li>字符串比较<ul>
<li><p><code>=</code>:等于</p>
</li>
<li><p><code>!=</code>:不等于</p>
</li>
<li><p><code>-z</code>:[ -z $1 ]检测字符串是否为空,如果为空，那么结果为真</p>
</li>
<li><p><code>-n</code>:[ -n $1 ]检测字符串是否不为空</p>
</li>
<li><p><code>在进行字符串比较时，最好为字符串加上引号，并且等号两侧留有空格</code></p>
</li>
</ul>
</li>
<li>文件比较<ul>
<li><code>file1 -nt file2</code>:判断文件1修改时间是否比文件2新</li>
<li><code>file1 -ot file2</code>:判断文件1修改时间是否比文件2旧</li>
</ul>
</li>
<li>逻辑运算<ul>
<li><code>-a、-o、!</code>:类 1 </li>
<li><code>&amp;&amp;、||</code>:类 2 <code>链接两个命令</code> 有断路功能</li>
</ul>
</li>
</ul>
</li>
<li>循环控制语句<ul>
<li><code>break</code>:结束退出循环</li>
<li><code>continue</code>:跳出本次循，不执行 continue 本次循环内后面的代码</li>
</ul>
</li>
<li>其他<ul>
<li><code>shift</code>:删除第一格位置参数,后面如果有全部往左移动一格</li>
<li><code>exit</code>:直接退出程序<br><code>exit 1-255</code>:程序结束后返回值，通过<code>$?</code>获取，程序正常结束值为 0</li>
</ul>
</li>
</ul>
<h3 id="字符串"><a href="#字符串" class="headerlink" title="字符串"></a>字符串</h3><ul>
<li>获取字符串长度 $</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">lzoxun</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2023/07/22/linux/linux-shell/">http://example.com/2023/07/22/linux/linux-shell/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">学习笔记</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/07/22/linux/linux-servers/" title="linux服务"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">linux服务</div></div></a></div><div class="next-post pull-right"><a href="/2023/07/22/linux/linux-vim/" title="vim"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">vim</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">lzoxun</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">108</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/liaozhongxun"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/liaozhongxun" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:869664233@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">这是我的文档</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#shell-%E8%84%9A%E6%9C%AC"><span class="toc-number">1.</span> <span class="toc-text">shell 脚本</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A6%82%E8%BF%B0"><span class="toc-number">1.1.</span> <span class="toc-text">概述</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%80%E5%90%AF-shell"><span class="toc-number">1.2.</span> <span class="toc-text">开启 shell</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%A7%E8%A1%8C"><span class="toc-number">1.3.</span> <span class="toc-text">执行</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E7%9A%84-bash-%E8%AF%AD%E5%8F%A5"><span class="toc-number">1.4.</span> <span class="toc-text">常用的 bash 语句</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%AD%E6%B3%95"><span class="toc-number">1.5.</span> <span class="toc-text">语法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-number">1.6.</span> <span class="toc-text">字符串</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-11/" title="win 11 set">win 11 set</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-gitbash/" title="git bash">git bash</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-wsl/" title="wsl">wsl</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-main/" title="window">window</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/web/%E5%85%BC%E5%AE%B9%E9%97%AE%E9%A2%98/" title="兼容问题">兼容问题</a><time datetime="2023-07-22T07:14:09.699Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By lzoxun</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><div class="js-pjax"></div><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-nest.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/haruto.model.json"},"display":{"position":"right","width":100,"height":200,"right":300},"mobile":{"show":true}});</script></body></html>